<template>
  <div class="user">
    <!-- 输入框 -->
    <div>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input v-model="input.query" placeholder="搜索..." clearable />
        </el-col>
        <el-button
          type="info"
          color="rgb(245,247,250)"
          :icon="Search"
          @click="cha"
        ></el-button>
        <el-button @click="dialogVisible = true">添加新用户</el-button>
        <el-dialog
          v-model="dialogVisible"
          title="添加用户"
          width="55%"
          :before-close="handleClose"
        >
          <div v-if="showtime">
            <el-form
              ref="formRef"
              :model="ruleForm"
              label-width="120px"
              class="demo-dynamic"
              :rules="rules"
            >
              <el-form-item label="用户名" prop="name">
                <el-input v-model="ruleForm.name" :disabled="!isshow" />
              </el-form-item>
              <el-form-item label="密码" prop="pass" v-if="isshow">
                <el-input
                  v-model="ruleForm.pass"
                  type="password"
                  autocomplete="off"
                />
              </el-form-item>
              <el-form-item prop="email" label="邮箱">
                <el-input v-model="ruleForm.email" />
              </el-form-item>
              <el-form-item label="手机号" prop="age">
                <el-input
                  v-model.number="ruleForm.age"
                  type="text"
                  autocomplete="off"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm(formRef)"
                  >确定</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <div v-else>
            <div>
              当前用户: <span>{{ ruleForm.name }}</span>
            </div>
            <div>
              当前角色: <span>{{ ruleForm.role_name }}</span>
            </div>
            <div class="example-block">
              <span class="example-demonstration">角色分配:</span>
              <el-form-item label="Activity zone">
                <el-select v-model="ssss" placeholder="" @change="changed">
                  <el-option
                    v-for="item in rouls.arr"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button
                v-if="showtime"
                type="primary"
                @click="submitForm(formRef)"
                >确认</el-button
              >
              <el-button v-else type="primary" @click="feipei">确认</el-button>
            </span>
          </template>
        </el-dialog>
      </el-row>
    </div>
    <!-- 展示内容区域 -->
    <div class="data_zhanshi" v-if="shuju.object">
      <el-table :data="shuju.object" stripe style="width: 100%">
        <el-table-column
          :width="item.width"
          :prop="item.prop"
          :label="item.label"
          v-for="(item, index) in options"
          :key="index"
        >
          <template v-slot="{ row }" v-if="item.prop === 'mg_state'">
            <el-switch v-model="row.mg_state" @change="xiugai(row)"></el-switch>
          </template>
          <template v-else-if="item.prop === 'action'" v-slot="{ row }">
            <el-tooltip content="编辑" placement="top">
              <el-button
                type="primary"
                size="small"
                :icon="Edit"
                @click="bianchu(row, '编辑')"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click="bianchu(row, '删除')"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="分配角色" placement="top">
              <el-button
                type="warning"
                size="small"
                :icon="Setting"
                @click="bianchu(row, '分配角色')"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <div class="fenyeqi">
        <el-pagination
          v-model:currentPage="input.pagenum"
          v-model:page-size="input.pagesize"
          :page-sizes="[2, 5, 10, 15]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { apis } from '@/http/api';
import { ElMessageBox } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { options } from '@/utils/opiton';
import { Edit, Setting, Delete, Search } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
//表单验证
const formRef = ref<FormInstance>();
const ruleForm = reactive({
  name: '',
  pass: '',
  email: '',
  age: '',
  role_name: 0,
});
//验证规则
const rules = ref({
  name: [
    { required: true, message: '请填写名称', trigger: 'blur' },
    { type: 'string', message: '长度为3~5', trigger: 'blur' },
  ],
  pass: [
    { required: true, message: '请填密码' },
    {
      type: 'string',
      message: 'age must be a number',
    },
  ],
  email: [
    {
      required: true,
      message: '必须填写邮箱',
      trigger: 'blur',
    },
    {
      type: 'email',
      message: '请填写正确邮箱',
      trigger: ['blur', 'change'],
    },
  ],
  age: [
    { required: true, message: '请填写手机号' },
    { type: 'number', message: 'age must be a number' },
  ],
});
//获取数据
const shuju = reactive({
  object: null as any,
});
const rouls = reactive({
  arr: null as any,
});
//初始化数据
onMounted(() => {
  huoqu(input.value.pagenum, input.value.pagesize);
});
const huoqu = (pagenum: number, pagesize: number, val?: string) => {
  const a = apis.getuser(pagenum, pagesize, val).then(({ data }) => {
    shuju.object = data.users;
    total.value = data.total;
    // console.log(data);
  });
  const b = apis.getsqx().then(({ data }) => {
    rouls.arr = data;
    // console.log(data);
  });
};
//显示表单
const isshow = ref(true);
//展示表单
const showtime = ref(true);
//组件需求
const input = ref({
  query: '',
  pagenum: 1,
  pagesize: 2,
});
const dialogVisible = ref(false);

const value1 = reactive({
  id: 0,
});
//添加表单点×提醒
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('你确定吗?')
    .then(() => {
      done();
    })
    .catch(() => {});
};
//查找数据
const cha = () => {
  huoqu(input.value.pagenum, input.value.pagesize, input.value.query);
};
//分页器
const total = ref(0);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const handleSizeChange = (val: number) => {
  input.value.pagenum = 1;
  input.value.pagesize = val;
  huoqu(input.value.pagenum, input.value.pagesize);
};
const handleCurrentChange = (val: number) => {
  input.value.pagenum = val;
  huoqu(input.value.pagenum, input.value.pagesize);

  console.log(`current page: ${val}`);
};
//修改用户状态
const xiugai = (val: any) => {
  const a = apis.postzt(val.id, val.mg_state).then((data) => {
    console.log(data);
    if (data.meta.status == 200) {
      ElMessage({
        message: '操作成功',
        type: 'success',
      });
    } else {
      ElMessage.error('操作失败!');
    }
  });
  // console.log(a);
};

//确认按钮加一些功能
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      console.log(valid);
      dialogVisible.value = false;
      if (isshow.value == true) {
        apis.postsj(ruleForm);
        ElMessage({
          message: '添加成功',
          type: 'success',
        });
      } else {
        apis.putbj(value1.id, ruleForm.email, ruleForm.age);
        ElMessage({
          message: '编辑成功',
          type: 'success',
        });
      }

      shuju.object = null;
      huoqu(input.value.pagenum, input.value.pagesize);
    } else {
      return false;
    }
  });
};
//分配
const feipei = () => {
  apis.postxg(value1.id, ruleForm.role_name);
  ElMessage({
    message: '分配成功',
    type: 'success',
  });
  dialogVisible.value = false;
};
//事件监听
watch(dialogVisible, (newName, oldName) => {
  if (newName == false) {
    ruleForm.age = '';
    ruleForm.email = '';
    ruleForm.name = '';
    ruleForm.pass = '';
    showtime.value = true;
    isshow.value = true;
  }
});

//点击编辑
const bianchu = (val: any, id?: string) => {
  let a = JSON.parse(JSON.stringify(val));
  ruleForm.age = a.mobile;
  ruleForm.email = a.email;
  ruleForm.name = a.username;
  ruleForm.role_name = a.role_name;
  value1.id = a.id;
  if (id == '删除') {
    showtime.value = true;
    apis.delsc(a.id);
    huoqu(input.value.pagenum, input.value.pagesize);
    ElMessage({
      message: '删除成功',
      type: 'success',
    });
  } else if (id == '编辑') {
    dialogVisible.value = true;
    isshow.value = false;
    showtime.value = true;
  } else {
    //分配角色
    console.log(a);

    dialogVisible.value = true;
    showtime.value = false;
  }
};

//
const ssss = ref([]);

const props = {
  expandTrigger: 'hover',
};

const changed = (val: any)  => {
  ruleForm.role_name = val;
  console.log(val);
};
</script>

<style lang="less" scoped>
.data_tou {
  height: 44px;
}
.data_shuru {
  width: 567px;
  height: 260px;
  box-sizing: border-box;
  .data_chang {
    width: 388px;
  }
  p {
    margin-top: 10px;
  }
}
//展示
.data_zhanshi {
  background-color: #fff;
  width: 100%;
}
//分页器
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
//角色分配
.example-block {
  margin: 10px 0;
}
</style>
